package com.m3958.firstgwt.server.command;

import java.io.IOException;

import net.sf.json.JSONObject;

import com.m3958.firstgwt.client.types.SmartSubOperationName;
import com.m3958.firstgwt.server.exception.SmartJpaException;
import com.m3958.firstgwt.server.model.BaseModel;
import com.m3958.firstgwt.server.response.ErrorMessageResponse;

public class UpdateCommand extends BaseCommand implements Command{
	
	private JSONObject result = null;
	
	private boolean writeResponse = true;

	@Override
	public void execute() throws SmartJpaException, IOException{

		SmartSubOperationName sson = SmartSubOperationName.NO_SUB_OPERATION;
		
		try {
			sson = SmartSubOperationName.valueOf(reqPs.getSubOpType());
		} catch (Exception e) {}
		
		switch (sson) {
		default:
			result = smartUpdate();
			break;
		}
		
		
		if(writeResponse){
			JSONObject m3958jo = new JSONObject();
			m3958jo.element("tid", reqPs.getTid());
			if(!errors.isEmpty()){
				result = injector.getInstance(ErrorMessageResponse.class).getJsonObject();
			}
			result.getJSONObject("response").element("m3958extra", m3958jo);
			if(reqPs.isJsonp()){
				autils.writeJsonpResponse(res, result.toString(), reqPs.getStringValue("callback"));
			}else{
				if(reqPs.isIframe()){
					irss.addIframeResult(reqPs.getTid(), result.toString());
					autils.writeHtmlResponseWithTemplate(res, "", "");
				}else{
					autils.writeJsonResponse(res,result.toString());
				}
			}
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private JSONObject smartUpdate() throws SmartJpaException {
		BaseModel model = getBaseModelFromParams();
		BaseModel bm = getDao().smartUpdateBaseModel(model);
		return  autils.getListResponse(bm,reqPs.getJsonv());
	}

	@Override
	public String getResult() {
		return result.toString();
	}
	
	@Override
	public void execute(boolean writeResponse) throws SmartJpaException,
			IOException {
		this.writeResponse = writeResponse;
		execute();
	}

}
